package com.qutan.app.core.manager;

import com.alibaba.dubbo.config.annotation.Service;
import com.i7time.entity.Info;
import com.i7time.service.InfoService;
import com.qutan.app.core.cache.InfoCache;
import com.qutan.app.core.repository.InfoRepository;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * Created by pengweiyuan on 6/14/16.
 */
@Service(version = "1.0.0", interfaceClass = InfoService.class)
public class InfoManager implements InfoService {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(InfoManager.class);

    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private InfoCache infoCache;

    @Override
    public List<Info> getInfoBySceneId(long sceneId) {
        return infoCache.getInfoListBySceneId(sceneId);
    }

    @Override
    public Info addInfo(long sceneId, String name, String title, String content, String avatar) {
        try {
            com.qutan.app.core.domain.Info info = new com.qutan.app.core.domain.Info();
            info.setSceneId(sceneId);
            info.setAvatar(avatar);
            info.setSceneName(name);
            info.setTitle(title);
            info.setContent(content);
            com.qutan.app.core.domain.Info save = infoRepository.save(info);
            infoCache.addInfo(save);
            return save.conver2EntityInfo();
        } catch (Exception e) {
            logger.error("addInfo error:", e);
            return null;
        }
    }

    @Override
    public Info updateInfo(long id, String name, String title, String content, String avatar) {
        try {
            com.qutan.app.core.domain.Info infoById = infoCache.getInfoById(id);
            if (infoById == null) return null;
            infoById.setSceneName(name);
            infoById.setTitle(title);
            infoById.setContent(content);
            infoById.setAvatar(avatar);
            infoRepository.save(infoById);
            infoCache.update(infoById);
            return infoById.conver2EntityInfo();
        } catch (Exception e) {
            logger.error(" updateInfo error id={}", id, e);
            return null;
        }
    }

    @Override
    public boolean deleteInfo(long infoId) {
        try {
            infoRepository.delete(infoId);
            //删除缓存
            infoCache.removeInfo(infoId);
            return true;
        } catch (Exception e) {
            logger.error(" deleteInfo error id={}", infoId, e);
            return false;
        }
    }

    /**
     * 删除资讯根据场景ID
     *
     * @param sceneId
     * @return
     */
    public boolean deleteAllBySceneId(long sceneId) {
        try {
            infoRepository.deleteBySceneId(sceneId);
            return infoCache.removeBySceneId(sceneId);
        } catch (Exception e) {
            logger.error(" deleteAllBySceneId error id={}", sceneId, e);
            return false;
        }
    }


}
